from client_resource.base_resource import BaseResource
import json
from elasticsearch import Elasticsearch
from elasticsearch import helpers


class EsClient(BaseResource):
    def __init__(self, init_config):
        super().__init__(init_config)

    def get_result(self, config):
        pass

    def get_client(self):
        _es = Elasticsearch(host=self.config["host"], port=self.config["port"])
        if _es.ping():
            return _es
        else:
            print("could not connect to es ")

    def create_index(self, index_name, body_file):
        """
        根据../data/es_index/mashups.json创建mashups index
        :return:
        """
        es_object = self.get_client()
        created = False
        settings = json.load(open(body_file))
        try:
            if not es_object.indices.exists(index_name):
                es_object.indices.create(index=index_name, ignore=400, body=settings)
                print("create index success")
            created = True
        except Exception as ex:
            print(str(ex))
        finally:
            print(created)
            return created

    def post_query(self, index, doc_type, body):
        """
        传递query,得到结果
        :return:
        """
        es = self.get_client()
        es_result = es.search(index=index, doc_type=doc_type, body=body)
        data_list = [res["_source"] for res in es_result["hits"]["hits"]]

        return data_list

    def process_result(self):
        pass

    def run(self) -> None:
        if not self.args:
            print("es_client service start without init")
            return
        # 执行run 函数
